package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.sql.Wrapper;
import java.util.HashMap;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto dto) {
        /**
         * 1.正常登陆，给予领牌
         * 2.非正常登陆返回结果集
         */
        //正常登陆
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
//查询用户
            //获取用户的手机号，通过手机号进行查询
            ApUser apuser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            //进行判断用户是否为空
            if (apuser == null) {
//等于null 返回结果集
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不在");
            }
            //判断用户的密码和盐
            String password = dto.getPassword();
            String salt = apuser.getSalt();
//进行MD5加密"

            password = MD5Utils.encodeWithSalt(password, salt);
            if (!password.equals(apuser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

            }
            //登陆成功
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apuser.getId().longValue()));
            apuser.setPassword(" ");
            apuser.setSalt(" ");
            map.put("user",apuser);
            return  ResponseResult.okResult(map);
        }else {
            //游客
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }
}
